module Lib {
    export class Hashmap{
        map = [];
        add(k,v){
            if (!this.map.hasOwnProperty(k)) {
                this.map[k] = v;
            }
        }
        remove(k){
            if (this.map.hasOwnProperty(k)) {
                delete this.map[k];
            }
        }
        update(k,v){
            this.map[k] = v;
        }
        
        clear(){
            for (let k in this.map) {
                if (this.map.hasOwnProperty(k)) {
                    delete this.map[k];
                }
            }
        }
       empty(){
           for (let k in this.map) {
                if (this.map.hasOwnProperty(k)) {
                    return false;
                }
            }
            return true;
       }
       has(k) {
            let type = typeof k;
            if (type === 'string' || type === 'number') {
                return this.map.hasOwnProperty(k);
            }
            return false;
       }
      
       find(k) {
            let type = typeof k;
            if (type === 'string' || type === 'number' && this.has(k)) {
                return this.map[k];
            }
            return null;
        }  
   
    }
    export class Mqant{
        public curr_id:number = 0;
        public client:Paho.MQTT.Client = null;
        //:new hashmap(),
        public waiting_queue:Lib.Hashmap = new Lib.Hashmap();
        private static instance:Mqant;
        public constructor() {

        }
        public static getInstance():Mqant
        {
            if(!this.instance)
            {
                this.instance = new Mqant();
            }
            return this.instance;
        }
        public init(prop){
            prop["onFailure"]=prop["onFailure"]||function () {
                egret.log("onFailure");
            }
            prop["onConnectionLost"]=prop["onConnectionLost"]||function (responseObject) {
                if (responseObject.errorCode !== 0) {
                    egret.log("onConnectionLost:" + responseObject.errorMessage);
                    egret.log("连接已断开");
                }
            }
            prop["useSSL"]=prop["useSSL"]||false;
            this.client = new Paho.MQTT.Client(prop["host"], prop["port"], prop["client_id"]);
            this.client.connect({
                onSuccess: prop["onSuccess"],
                onFailure: prop["onFailure"],
                mqttVersion: 3,
                useSSL:prop["useSSL"],
                cleanSession: true,
            });//连接服务器并注册连接成功处理事件
            this.client.onConnectionLost = prop["onConnectionLost"] ;//注册连接断开处理事件
            this.client.onMessageArrived = onMessageArrived;//注册消息接收处理事件
       
            var self=this;
            function onMessageArrived(message) {
                egret.log("接收中...");
                var callback=self.waiting_queue.find(message.destinationName);
                if(typeof(callback)!="undefined"){
                    //有等待消息的callback 还缺一个信息超时的处理机制
                    var h=message.destinationName.split("/")
                    if(h.length>2){
                        //这个topic存在msgid 那么这个回调只使用一次
                        self.waiting_queue.remove(message.destinationName)
                    }
                    callback(message);
                }
                if(message.destinationName == "User/OnUpdateUser"){
                    Dispatcher.ins.dispatchEvent(new GameEvent("home",{"note":"update","data":JSON.parse(message.payloadString)}));
                }
                if(message.destinationName == "User/OnUpEnergy"){
                    Dispatcher.ins.dispatchEvent(new GameEvent("home",{"note":"energy","data":JSON.parse(message.payloadString)}));
                }
                if(message.destinationName == "User/OnFirstGain"){
                    Dispatcher.ins.dispatchEvent(new GameEvent("home",{"note":"harvest","data":JSON.parse(message.payloadString)}));
                }
            }
        }
        /**
         * 向服务器发送一条消息
         * @param topic
         * @param msg
         * @param callback
         */
        public request(topic,msg,callback){
            this.curr_id+=1;
            var topicStr=topic+"/"+this.curr_id; //给topic加一个msgid 这样服务器就会返回这次请求的结果,否则服务器不会返回结果
            var payload=JSON.stringify(msg);
            this.on(topicStr,callback);
            this.client.send(topicStr,payload ,1);
        }
        /**
         * 向服务器发送一条消息,但不要求服务器返回结果
         * @param topic
         * @param msg
         */
        public requestNR(topic,msg){
            var payload=JSON.stringify(msg);
            this.client.send(topic,payload ,1);
        }
        /**
         * 监听指定类型的topic消息
         * @param topic
         * @param callback
         */
        public on(topic,callback){
            this.waiting_queue.add(topic,callback); //添加这条消息到等待队列
        }

    }
}
